package org.ztr.yanai.blog.validator;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.ztr.yanai.blog.annotation.IdCard;

import java.util.regex.Pattern;

/**
 * @Author: ZhaoTR
 * @Date: Created in 2025/11/22 14:30
 * @Description: 身份证号校验器
 * @Version: 1.0
 */
public class IdCardValidator implements ConstraintValidator<IdCard, String> {

    private static final Pattern ID_CARD_PATTERN = Pattern.compile("^[1-9]\\d{5}(18|19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\\d|3[01])\\d{3}[\\dXx]$");

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        // 允许为空，由@NotBlank等注解控制是否必填
        if (value == null || value.trim().isEmpty()) {
            return true;
        }
        return ID_CARD_PATTERN.matcher(value).matches();
    }
}
